import {
  ArgumentsHost,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';

export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    let status: number;
    let errorResponse: string | object;

    if (exception instanceof HttpException) {
      status = exception.getStatus();
      errorResponse = exception.getResponse();
    } else {
      status = HttpStatus.INTERNAL_SERVER_ERROR;
      errorResponse = exception;
    }

    // 这里需要判断错误响应是否是数组，并进行相应处理
    let errorMessage: string | unknown = 'Internal Server Error';
    if (
      typeof errorResponse === 'object' &&
      errorResponse !== null &&
      'message' in errorResponse
    ) {
      if (Array.isArray(errorResponse.message)) {
        errorMessage = errorResponse.message[0];
      } else {
        errorMessage = errorResponse.message;
      }
    } else if (typeof errorResponse === 'string') {
      errorMessage = errorResponse;
    }

    return response.status(status).json({
      code: status,
      msg: errorMessage || '服务异常',
      result: null,
    });
  }
}
